import Koa from "koa";
import jwt, { VerifyErrors } from "jsonwebtoken";
import { whiteRequest } from "./config";
import { response } from "../utils/http";
export default async function useMiddleware(ctx: Koa.Context, next: Koa.Next) {
  let secret = "suodesinai";

  if (whiteRequest.some((item) => ctx.request.path.startsWith(item))) {
    await next();
  } else {
    let token = ctx.headers.token as unknown as string;
    if (!token) {
      ctx.body = response(401, null, "未登录！");
    } else {
      const jwtInfo = await getJwtInfo(token, secret);
      if (jwtInfo.err) {
        ctx.body = response(500, null, "无效Token！");
      } else {
        ctx.state.user = jwtInfo.decoded;
        await next();
      }
    }
  }
}

// 验证jwt
export function getJwtInfo(
  token: string,
  secret: string,
): Promise<{ err: VerifyErrors | null; decoded: any }> {
  return new Promise((resolve, reject) => {
    jwt.verify(token, secret, (err, decoded) => {
      resolve({ err, decoded });
    });
  });
}
